package com.gt.gcm;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

import com.google.android.gcm.GCMRegistrar;

/**
 * 
 * Register a receiver if you want to handle the message from GCM yourself.
 * What is the action and extra for a receiver, please see the field BROADCAST_ACTION_MESSAGE and  EXTRA_NAME_MESSAGE.
 * 
 * Must set the string values for sender id, url. See the section "push message" in strings.xml
 * 
 * @author Jigar
 *
 */
public class GCMManager {

	private static final String TAG="GCMManager";
	
	private static Context mContext = null;
	private static String senderID = null;

	private static String serverUrlRegister = null;
	private static String serverUrlUnregister = null;

	private static int timeConnectTimeout = 15000;
	private static int timeReadTimeout = 25000;
	
	public static final String BROADCAST_ACTION_MESSAGE="com.gt.gcm.GCMManager.BROADCAST_ACTION_MESSAGE";
	public static final String EXTRA_NAME_MESSAGE="EXTRA_NAME_MESSAGE";
	
//	private static AsyncTask<Void, Void, Void> mRegisterTask;
	
	public static final int WHEN_PUSH_MESSAGE_NONE=0;
	public static final int WHEN_PUSH_MESSAGE_SHOW_NOTIFICATION=101;
	public static final int WHEN_PUSH_MESSAGE_SHOW_DIALOG=102;
	private static int behaviorWhenPushMessage=WHEN_PUSH_MESSAGE_NONE;
	private static boolean isNeedWifiMac;
	
	
	private GCMManager() {

	}

	public static void onCreate(Context context, String senderID) {
		mContext = context;
		GCMManager.senderID = senderID;
	}

	public static void start() {
		GCMRegistrar.checkDevice(mContext);
		// Make sure the manifest was properly set - comment out this line
		// while developing the app, then uncomment it when it's ready.
		GCMRegistrar.checkManifest(mContext);

		final String regId = GCMRegistrar.getRegistrationId(mContext);
		if (regId==null || regId.equals("")) {
			// Automatically registers application on startup.
			Log.i(TAG, "start>>>senderID="+senderID);
			GCMRegistrar.register(mContext, senderID);
		} else {
			// Device is already registered on GCM, check server.
			if (GCMRegistrar.isRegisteredOnServer(mContext)) {
				// Skips registration.
				Log.i(TAG, "GCMRegistrar.isRegisteredOnServer() returns true");
//				mDisplay.append(getString(R.string.already_registered) + "\n");
			} else {
/*				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						boolean registered = ServerUtilities.register(mContext,regId);
						// At this point all attempts to register with the app
						// server failed, so we need to unregister the device
						// from GCM - the app will try to register again when
						// it is restarted. Note that GCM will send an
						// unregistered callback upon completion, but
						// GCMIntentService.onUnregistered() will ignore it.
						if (!registered) {
							GCMRegistrar.unregister(mContext);
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						mRegisterTask = null;
					}

				};
				mRegisterTask.execute(null, null, null);*/
				
				final Context context = mContext;
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						boolean registered = ServerUtilities.register(mContext,regId);
						if(!registered) {
							GCMRegistrar.unregister(context);
						}
					}
				}).start();
				
			}
		}
	}
	
	public static String getRegistrationId(){
		return GCMRegistrar.getRegistrationId(mContext);
	}
	
	public static void onDestroy() {
//        if (mRegisterTask != null) {
//            mRegisterTask.cancel(true);
//        }
        GCMRegistrar.onDestroy(mContext);
        mContext = null;
        serverUrlRegister = null;
        serverUrlUnregister = null;
    }
	
//	public static void startByGtHKType(String language) {
//		startByGtHKType(Constants.Languages.getByString(language));
//	}
	
	/**
	 * This method for Youth. The response content from server is xml.
	 * @param language
	 */
	public static void startByGtHKType(final String language) {
		startByGtHKType(language, null);
	}
	
	/**
	 * This method for others. The response content from server is plist file, so parse it with resultChecker.
	 * @param language
	 * @param resultChecker
	 */
	public static void startByGtHKType(final String language,final ResultChecker resultChecker) {
		startByGtHKType(language, resultChecker, false);
	}
	
	/**
	 * This method for others. The response content from server is plist file, so parse it with resultChecker.
	 * @param language
	 * @param resultChecker
	 */
	public static void startByGtHKType(final String language,final ResultChecker resultChecker, final boolean sync) {
		GCMRegistrar.checkDevice(mContext);
		GCMRegistrar.checkManifest(mContext);

		final String regId = GCMRegistrar.getRegistrationId(mContext);
		if (regId==null || regId.equals("")) {
			Log.i(TAG, "startByGtHKType>>>senderID="+senderID);
			GCMRegistrar.register(mContext, senderID);
		} else {
//			mRegisterTask = new AsyncTask<Void, Void, Void>() {
//				@Override
//				protected Void doInBackground(Void... params) {
//					boolean registered = GtServerUtilities.registerGtHkServer(mContext, regId, language,resultChecker);
//					Log.e(TAG, "startByGtHKType>>>registered="+registered);
//					return null;
//				}
//
//				@Override
//				protected void onPostExecute(Void result) {
//					mRegisterTask = null;
//				}
//
//			};
//			mRegisterTask.execute(null, null, null);
			
			registerToHKServer(regId, language, resultChecker, sync);
			
		}
	}
	
	public static void startByCustomType(final ServerRegister serverRegister,final String language) {
		GCMRegistrar.checkDevice(mContext);
		GCMRegistrar.checkManifest(mContext);

		final String regId = GCMRegistrar.getRegistrationId(mContext);
		if (regId==null || regId.equals("")) {
			Log.i(TAG, "startByCustomType>>>senderID="+senderID);
			GCMRegistrar.register(mContext, senderID);
		} else {
//			mRegisterTask = new AsyncTask<Void, Void, Void>() {
//				@Override
//				protected Void doInBackground(Void... params) {
//					boolean registered = serverRegister.registerToServer(mContext, regId, language);
//					Log.e(TAG, "startByCustomType>>>registered="+registered);
//					return null;
//				}
//
//				@Override
//				protected void onPostExecute(Void result) {
//					mRegisterTask = null;
//				}
//
//			};
//			mRegisterTask.execute(null, null, null);
			
			registerToHKServer(regId, language);
			
		}
	}
	
	

	public static boolean isNeedWifiMac() {
		return isNeedWifiMac;
	}

	public static void setNeedWifiMac(boolean isNeedWifiMac) {
		GCMManager.isNeedWifiMac = isNeedWifiMac;
	}

	public static String getSenderID() {
		return senderID;
	}

	public static void setSenderID(String senderID) {
		GCMManager.senderID = senderID;
	}

	public static String getServerUrlRegister() {
		return serverUrlRegister;
	}

	public static void setServerUrlRegister(String serverUrlRegister) {
		GCMManager.serverUrlRegister = serverUrlRegister;
	}

	public static String getServerUrlUnregister() {
		return serverUrlUnregister;
	}

	public static void setServerUrlUnregister(String serverUrlUnregister) {
		GCMManager.serverUrlUnregister = serverUrlUnregister;
	}

	public static int getTimeConnectTimeout() {
		return timeConnectTimeout;
	}

	public static void setTimeConnectTimeout(int timeConnectTimeout) {
		GCMManager.timeConnectTimeout = timeConnectTimeout;
	}

	public static int getTimeReadTimeout() {
		return timeReadTimeout;
	}

	public static void setTimeReadTimeout(int timeReadTimeout) {
		GCMManager.timeReadTimeout = timeReadTimeout;
	}
	
	public static void setExtraNameMessage(String name){
		GCMIntentService.setExtraNameMessage(name);
	}

	
	public static int getBehaviorWhenPushMessage() {
		return behaviorWhenPushMessage;
	}

	public static void setBehaviorWhenPushMessage(int behaviorWhenPushMessage) {
		GCMManager.behaviorWhenPushMessage = behaviorWhenPushMessage;
	}

	///=================== UI =========================
	/**
	 * 
	 * @param context A Context of the application package implementing this class.
	 * @param cls The component class that is to be used for the intent.
	 * @param message
	 */
	public static void showNotification(Context context, Class<?> cls, int resIcon,String message) {
		showNotification(context, cls, R.string.app_name, resIcon, message);
	}
	public static void showNotification(Context context, Class<?> cls,int resAppName, int resIcon,String message) {
		int icon = R.drawable.ic_stat_gcm;
        if(resIcon!=0){
        	icon=resIcon;
        }
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);
        String title = context.getString(R.string.app_name);
        Intent notificationIntent = new Intent(context, cls);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notification);
    }
	
	public static void showDialog(Context context, Class<?> cls,String message){
		//TODO
	}
	
	private static void registerToHKServer(final String regId, final String language) {
		registerToHKServer(regId, language, null, false);
	}
	
	private static void registerToHKServer(final String regId, final String language, final ResultChecker resultChecker, final boolean sync) {
		final Context context = mContext;
		if(sync) {
			if(resultChecker != null) {
				GtServerUtilities.registerGtHkServer(context, regId, language,resultChecker);
			}
			else {
				GtServerUtilities.registerGtHkServer(context, regId, language);
			}
		}
		else {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					if(resultChecker != null) {
						GtServerUtilities.registerGtHkServer(context, regId, language,resultChecker);
					}
					else {
						GtServerUtilities.registerGtHkServer(context, regId, language);
					}
				}
			}).start();
		}
	}
}
